<?php
namespace Rexzy\Http;

class Rules {
    public $rule;
    private $_ruleConfig;
    
    public function __construct( $ruleConfig ) { 
        $this->_ruleConfig = $ruleConfig;
        if ( $this->_ruleConfig['type'] == 'pathInfo' ) {
            if ( array_key_exists( 'PATH_INFO', $_SERVER ) ) {
                $this->rule = trim( $_SERVER['PATH_INFO'], '/' );
            }
            
        } else if ( $this->_ruleConfig['type'] == 'get' ) {
            if ( array_key_exists( 'r', $_GET ) ) {
                $this->rule = trim( $_GET['r'], '/' );
            }
        }
    }
    
    /**
     *  路由分发页面
     * 
     * @return string 编译过来后的真正链接
     */
    public function distribute() {
        foreach ( $this->_ruleConfig['rules'] as $key => $value ) {
            $key = str_replace( '/', '\/', trim( $key, '/' ) );
            $value = trim( $value, '/' );
            
            if ( preg_match_all( '/\[:(\w+)\]/', $key, $matches ) ) {
                $pattern = preg_replace( '/\[:(\w+)\]/', '([^\/]+)', $key );
                if ( preg_match( "/$pattern/", $this->rule, $matches2 ) ) {
                    $matches2 = array_splice( $matches2, 1 );
                    foreach ( $matches2 as $key1 => $value1 ) {
                            $value = str_replace( $matches[0][ $key1 ], $value1, $value );
                    }
                    return $value;
                }
            } else if ( preg_match_all( "/$key/", $this->rule, $matches ) ) {
                return preg_replace("/$key/", $value, $this->rule );
            } 
        }
        return $this->rule;
    }
    
}

